<script setup>
import {ref, computed, watch, onMounted} from 'vue';
import axios from "axios";
import {ElMessage} from "element-plus";

// 模拟数据
const stores = ref([]);

// 筛选条件
const searchStoreName = ref('');
const searchStatus = ref('');

// 筛选后的数据
const filteredStores = computed(() => {
  return stores.value.data || []; // 确保访问data属性
});
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalPages = ref(10);


// 页码按钮显示范围
const pageNumbers = computed(() => {
  const maxPagesToShow = 5;
  const half = Math.floor(maxPagesToShow / 2);
  let startPage = Math.max(1, currentPage.value - half);
  let endPage = Math.min(totalPages.value, startPage + maxPagesToShow - 1);

  if (endPage - startPage + 1 < maxPagesToShow) {
    startPage = Math.max(1, endPage - maxPagesToShow + 1);
  }

  return Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);
});

// 跳转页码
const jumpPage = ref(1);
const jumpToPage = () => {
  if (jumpPage.value >= 1 && jumpPage.value <= totalPages.value) {
    currentPage.value = jumpPage.value;
    initData();
  }
};

// 监听pageSize变化，重置当前页
watch(pageSize, () => {
  currentPage.value = 1;
  initData();
});
watch(pageNumbers, () => {
  initData();
});
// 弹窗相关
const showDialog = ref(false);
const isEdit = ref(false);
// 获取当前ISO格式时间
const currentTime = new Date().toISOString();
const form = ref({
  id: '',
  name: '',
  creatTime: currentTime,
  address: '',
  phone: '',
  people: '',
  status: '正常'
});

// 打开新增弹窗
const openAddDialog = () => {
  isEdit.value = false;
  form.value = {

  };
  showDialog.value = true;
};

// 打开编辑弹窗
const openEditDialog = (store) => {
  isEdit.value = true;

  form.value = { ...store };
  showDialog.value = true;
  console.log(form.value.id)

};

// 关闭弹窗
const closeDialog = () => {
  showDialog.value = false;
};

// 确认操作（新增或编辑）
const confirmAction = () => {
  if (isEdit.value) {

    // 编辑
    axios.post(`/store/updateStore/${form.value.id}`, form.value).then(response => {
      ElMessage.success(response.data);
      initData(); // 刷新列表
    }) .catch(error => {
      ElMessage.error('修改失败');
      console.error(error);
    });
  } else {
    console.log(form.value);
    // 新增
    axios.post('/store/addStore', form.value)
        .then(res => {
          ElMessage.success(res.data);
          initData(); // 刷新列表
        })
        .catch(error => {
          ElMessage.error('添加失败');
          console.error(error);
        });
  }
  closeDialog();
};

// 删除门店
const deleteStore = (store) => {
  axios.delete(`/store/deleteStore/${store.id}`).then(res => {
    ElMessage.success(res.data);
    initData();
  })
};
// 批量删除
const batchDelete = () => {
  console.log({data: selectedIds.value});
  axios.delete("/store/deleteChoises", {data: selectedIds.value}).then(res => {
    ElMessage.success(`成功删除 ${res.data.deletedCount} 项`);
    initData();
    selectedIds.value = []; // 清空选中项
  }).catch(error => {
    ElMessage.error('删除失败');
    console.error('删除错误:', error);
  });
}

// 选中的ID集合
const selectedIds = ref([]);

// 处理多选变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id); // 提取选中行的ID
};
// 筛选数据
const filterData = () => {

    // 构建查询参数（允许空值）
    const params = {
      status: searchStatus.value,
      search: searchStoreName.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };

    axios.post(`/store/searchStores`, null, { params }) // 注意 POST 传 query 参数的方式
        .then(res => {
          stores.value = res.data;
        });

};


// 加载表格
// 修改initData方法
const initData = () => {

  axios.get(`/store/getAll/${currentPage.value}/${pageSize.value}`,currentPage.value,pageSize.value).then((res) => {
    stores.value = res.data.obj; // 绑定完整响应对象
    totalPages.value = Math.ceil(res.data.obj.total / pageSize.value);
  })
}

onMounted(()=>{
  initData();
})
</script>

<template>
  <div class="container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>门店管理</h2>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-input">
        <label for="store-name">门店</label>
        <input type="text" v-model="searchStoreName" placeholder="请输入" />
      </div>
      <div class="filter-select">
        <label for="store-status">请选择门店状态</label>
        <select v-model="searchStatus">
          <option value="2">全部</option>
          <option value="1">正常</option>
          <option value="0">关闭</option>
        </select>
      </div>
      <button class="search-btn" @click="filterData">查询</button>
    </div>

    <!-- 数据表格 -->
    <div class="data-table">
      <div class="table-header">
        <h3>数据列表</h3>
        <button class="add-btn" @click="openAddDialog">新增门店</button>
        <button class="batch-delete-btn" @click="batchDelete">批量删除</button>
      </div>
      <table>
        <thead>
        <tr>
          <th>选择</th>
          <th>编号</th>
          <th>名称</th>
          <th>地址</th>
          <th>电话</th>
          <th>创建日期</th>
          <th>人数</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(store, index) in filteredStores" :key="index">
          <td>
            <input
                type="checkbox"
                :value="store.id"
                v-model="selectedIds"
            />
          </td>
          <td>{{ store.id }}</td>
          <td>{{ store.name }}</td>
          <td>{{ store.address }}</td>
          <td>{{ store.phone }}</td>
          <td>{{ store.createTime }}</td>
          <td>{{ store.members }}</td>
          <td>{{ store.status }}</td>
          <td>
            <button class="edit-btn" @click="openEditDialog(store)">编辑</button>
            <button class="delete-btn" @click="deleteStore(store)">删除</button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
    <!-- 分页组件 -->
    <div class="pagination">
      <button :disabled="currentPage === 1" @click="currentPage = 1">首页</button>
      <button :disabled="currentPage === 1" @click="currentPage--">上一页</button>
      <div class="page-numbers">
        <button
            v-for="page in pageNumbers"
            :key="page"
            :class="{ active: page === currentPage }"
            @click="currentPage = page"
        >
          {{ page }}
        </button>
      </div>
      <button :disabled="currentPage === totalPages" @click="currentPage++">下一页</button>
      <button :disabled="currentPage === totalPages" @click="currentPage = totalPages">末页</button>
      <div class="page-info">
        <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
        <select v-model="pageSize">
          <option value="10">每页 10 条</option>
          <option value="20">每页 20 条</option>
          <option value="50">每页 50 条</option>
          <option value="100">每页 100 条</option>
        </select>
        <div class="jump-to">
          <input type="number" v-model.number="jumpPage" min="1" :max="totalPages" />
          <button @click="jumpToPage">跳转</button>
        </div>
      </div>
    </div>
    <!-- 新增/编辑弹窗 -->
    <div class="dialog" v-if="showDialog">
      <div class="dialog-content">
        <h3>{{ isEdit ? '编辑门店' : '新增门店' }}</h3>
        <div class="form-group">
          <label for="name">名称</label>
          <input type="text" v-model="form.name" />
        </div>
        <div class="form-group">
          <label for="address">地址</label>
          <input type="text" v-model="form.address" />
        </div>
        <div class="form-group">
          <label for="phone">电话</label>
          <input type="text" v-model="form.phone" />
        </div>
        <div class="form-group">
          <label for="people">人数</label>
          <input type="number" v-model="form.members" />
        </div>
        <div class="form-group">
          <label for="status">状态</label>
          <select v-model="form.status">
            <option value="1">正常</option>
            <option value="0">关闭</option>
          </select>
        </div>
        <div class="dialog-actions">
          <button class="cancel-btn" @click="closeDialog">取消</button>
          <button class="confirm-btn" @click="confirmAction">确认</button>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped>
/* 在style部分添加以下样式 */
.batch-delete-btn {
  padding: 8px 15px;
  background-color: #ff3333;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

.batch-delete-btn:hover {
  background-color: #cc0000;
}

/* 调整表头按钮布局 */
.table-header > div {
  display: flex;
  align-items: center;
}
/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.pagination button {
  padding: 6px 12px;
  margin: 0 5px;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination button.active {
  background-color: #ff6600;
  color: white;
  border-color: #ff6600;
}

.page-numbers {
  display: flex;
  align-items: center;
}

.page-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.page-info select {
  margin: 0 10px;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.jump-to {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.jump-to input {
  width: 50px;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
}

.jump-to button {
  margin-left: 5px;
  padding: 6px 12px;
}
.container {
  padding: 20px;
  font-family: Arial, sans-serif;
}

.page-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
}

.filter-input, .filter-select {
  margin-right: 15px;
}

.filter-input label, .filter-select label {
  margin-right: 5px;
}

input, select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-btn {
  padding: 8px 15px;
  background-color: #ff6600;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.data-table {
  background: white;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.add-btn {
  padding: 8px 15px;
  background-color: #ff6600;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.edit-btn, .delete-btn {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.edit-btn {
  background-color: #f0f0f0;
  margin-right: 5px;
}

.delete-btn {
  background-color: #ff6600;
  color: white;
}

.dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  width: 400px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.cancel-btn, .confirm-btn {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.cancel-btn {
  background-color: #f0f0f0;
}

.confirm-btn {
  background-color: #ff6600;
  color: white;
}
</style>